package com.zxw.hotel.common;


import com.zxw.hotel.model.clientmumber;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

public class ClientLoginInterceptor implements HandlerInterceptor {
    public static final String CLIENT_USER_KEY = "#client_user";

    @Override
    public boolean preHandle(HttpServletRequest req,
                             HttpServletResponse resp, Object handler) throws Exception {


        clientmumber user = (clientmumber) req.getSession().getAttribute(CLIENT_USER_KEY);

        if (user == null) {
            resp.setStatus(401);//设置响应状态码

            //判断是否ajax请求
            String ajaxFlag = req.getHeader("x-requested-with");
            if ("XMLHttpRequest".equals(ajaxFlag)) {//表示是ajax请求
                Tojson.writeJson(resp, Map.of("success", false, "code", "401"));
            } else {
                //重定向操作
                resp.sendRedirect(req.getContextPath() + "/client/login");
            }
            return false;
        }
        return true;
    }
}
